﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using DAL;

namespace PeisongWeb
{
    public partial class myRecipeList : buyerPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (hasPermission("FC",1))
                {
                    recipeCategory();
                    rptBind();
                    categoryBind();
                }
                else
                {
                    Library.Script.ClientMsgUrl("没有权限","index.html");
                    return;
                }
                if (hasPermission("FC", 2))
                {
                    btnSaveRecipe.Enabled = true;
                }
                else
                {
                    btnSaveRecipe.Enabled = false;
                }
            }
        }

        private void recipeCategory()
        {
            DataTable dt = logic.recipeCategory.select(logic.customer.getCompanyId());

            // 默认加载第一个类别
            if (dt.Rows.Count > 0 && dt.Rows[0]["rcid"] != null && dt.Rows[0]["name"] != null && (string.IsNullOrEmpty(Request.QueryString["category"]) && string.IsNullOrEmpty(Request.QueryString["name"])))
            {
                Response.Redirect(String.Format("buyer_myRecipeList.html?name={0}&category={1}", HttpUtility.UrlEncodeUnicode(dt.Rows[0]["name"].ToString()), dt.Rows[0]["rcid"]));
            }

            ddlRecipeCategory.DataSource = dt;
            ddlRecipeCategory.DataBind();

            rptRecipeCategoryList.DataSource = dt;
            rptRecipeCategoryList.DataBind();
        }

        private void categoryBind()
        {
            DataTable dt = logic.category.getByParent(0);
            rptCategory.DataSource = dt;
            rptCategory.DataBind();
        }
        private void rptBind()
        {

            int rcid = 0;
            lblRecipeCategoryName.Text = Request.QueryString["name"];
            StringBuilder where = new StringBuilder();
            where.AppendFormat(" 1=1 and [source]='2' and companyId={0}", logic.customer.getCompanyId());
            if (int.TryParse(Request.QueryString["category"], out rcid))
            {
                where.AppendFormat(" and rcid={0}", rcid);
            }

            DataSet recipeList = logic.recipe.select(where.ToString(), "inputDt DESC", AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex);
            if (recipeList.Tables.Count > 1)
            {
                AspNetPager1.RecordCount = Convert.ToInt32(recipeList.Tables[0].Rows[0][0]);
                rptRecipeList.DataSource = recipeList.Tables[1];
                rptRecipeList.DataBind();
            }
        }
        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            rptBind();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            rptBind();
        }
        protected void rptRecipeList_ItemCommand(object sender, CommandEventArgs e)
        {
            if (e.CommandName == "Del")
            {
                int recipeId = 0;
                int.TryParse(e.CommandArgument.ToString(), out recipeId);
                logic.recipe.delete(recipeId);
                rptBind();
                Library.Script.ClientMsg("删除成功!");
            }
        }
        protected void btnSaveRecipe_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(hdAction.Value))
            {
                int companyId = logic.customer.getCompanyId();
                if (txtDishName.Value!=hdCurrentDishName.Value)
                {
                    // 编辑系统菜谱转换成我的菜谱(菜谱名称唯一性判断)
                    bool isExists = logic.recipe.isExistsRecipeName(companyId, txtDishName.Value, "2");
                    if (isExists)
                    {
                        Library.Script.ClientMsg("您的菜谱列表中已经存在当前菜谱!您可以重新命名菜谱名称，然后点击保存.");
                        return;
                    } 
                }
                if (string.IsNullOrEmpty(hdProductIds.Value))
                {
                    Library.Script.ClientMsg("您未选择任何原料，不能保存当前菜谱！");
                    return;
                }
                int recipeId = 0;

                if (hdAction.Value == "Add")
                {
                    RecipeEntity recipe = new RecipeEntity();
                    recipe.Name = txtDishName.Value;
                    int rcid = 0;
                    int.TryParse(ddlRecipeCategory.SelectedValue, out rcid);
                    recipe.Rcid = rcid;
                    recipe.Description = "";
                    int sort = 0;
                    recipe.Sort = sort;
                    recipe.Source = "2";
                    recipe.IsShow = true;
                    recipe.IsRecommend = false;
                    recipe.Favorite = false;
                    recipe.CompanyId = companyId;

                    recipeId = logic.recipe.insert(recipe);
                }
                else if (hdAction.Value == "Edit")
                {
                    int.TryParse(hdCurrentRecipeId.Value, out recipeId);
                    if (recipeId != 0)
                    {
                        // 编辑
                        RecipeEntity recipe = logic.recipe.getById(recipeId);
                        int rcid = 0;
                        int.TryParse(ddlRecipeCategory.SelectedValue, out rcid);
                        recipe.Name = txtDishName.Value;
                        recipe.Rcid = rcid;
                        logic.recipe.update(recipe);
                        logic.recipeItem.delByRecipeId(recipeId);
                    }
                }

                SaveRecipeItems(recipeId);
               
                // 跳转
                String redirectURL = String.Format("buyer_myRecipeList.html?name={0}&category={1}", HttpUtility.UrlEncodeUnicode(ddlRecipeCategory.SelectedItem.Text), ddlRecipeCategory.SelectedValue);
                Library.Script.ClientMsgUrl("保存成功!", redirectURL);
            }
        }

        private void SaveRecipeItems(int recipeId)
        {
            if (!string.IsNullOrEmpty(hdProductIds.Value))
            {
                String[] ids = hdProductIds.Value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (String productId in ids)
                {
                    logic.recipeItem.insert(new RecipeItemEntity() { RecipeId = recipeId, ProductId = Convert.ToInt32(productId) });
                }
            }
        }
    }
}
